const db = require("@/db/index");

// 分页查询招聘计划
exports.queryRecruitmentPlan = (req, resp) => {
  try {
    const {
      pageSize = 10,
      pageNum = 1,
      staffName,
      position,
      audit,
      timeStart,
      timeEnd,
    } = req.body;

    // 构建查询条件
    let conditions = [];
    let params = [];

    if (staffName) {
      conditions.push("staff_name LIKE ?");
      params.push(`%${staffName}%`);
    }
    if (position) {
      conditions.push("position LIKE ?");
      params.push(`%${position}%`);
    }
    if (audit !== "") {
      conditions.push("audit = ?");
      params.push(audit);
    }
    if (timeStart && timeEnd) {
      conditions.push("time BETWEEN ? AND ?");
      params.push(timeStart, timeEnd);
    } else if (timeStart) {
      conditions.push("time >= ?");
      params.push(timeStart);
    } else if (timeEnd) {
      conditions.push("time <= ?");
      params.push(timeEnd);
    }

    const whereClause = conditions.length
      ? "WHERE " + conditions.join(" AND ")
      : "";

    // 查询总数
    const countSql = `SELECT COUNT(*) as total FROM recruitmentplan ${whereClause}`;
    db.query(countSql, params, (err, totalResult) => {
      if (err) return resp.err(err);
      const total = totalResult[0].total;

      // 查询数据
      const offset = (pageNum - 1) * pageSize;
      const dataSql = `
        SELECT *
        FROM recruitmentplan
        ${whereClause}
        ORDER BY time DESC, id DESC
        LIMIT ? OFFSET ?
      `;

      db.query(dataSql, [...params, pageSize, offset], (err, rows) => {
        if (err) return resp.err(err);
        resp.ok({
          total,
          list: rows,
          pageSize,
          pageNum,
        });
      });
    });
  } catch (error) {
    resp.err(error);
  }
};

// 新增招聘计划
exports.addRecruitmentPlan = (req, resp) => {
  try {
    const planInfo = req.body;

    // 必填字段校验
    if (!planInfo.post) return resp.err("招聘岗位不能为空");
    if (!planInfo.requirement) return resp.err("招聘要求不能为空");
    if (!planInfo.num) return resp.err("招聘人数不能为空");

    // 构建插入数据
    const insertData = {
      post: planInfo.post,
      requirement: planInfo.requirement,
      num: planInfo.num,
      staff_no: planInfo.staff_no || null,
      staff_name: planInfo.staff_name || null,
      position: planInfo.position || null,
      department_name: planInfo.department_name || null,
      process: planInfo.process || null,
      time: planInfo.time || new Date(),
      audit: planInfo.audit || 0,
      review_responses: planInfo.review_responses || null,
    };

    const insertSql = "INSERT INTO recruitmentplan SET ?";
    db.query(insertSql, insertData, (err, result) => {
      if (err) {
        console.error("新增失败:", err);
        return resp.err("新增失败: " + err.message);
      }
      resp.ok({ id: result.insertId }, "新增成功");
    });
  } catch (error) {
    console.error("新增异常:", error);
    resp.err("新增失败: " + error.message);
  }
};

// 删除招聘计划
exports.deleteRecruitmentPlan = (req, resp) => {
  try {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return resp.err("请选择要删除的记录");
    }

    const deleteSql = "DELETE FROM recruitmentplan WHERE id IN (?)";
    db.query(deleteSql, [ids], (err, result) => {
      if (err) {
        console.error("删除失败:", err);
        return resp.err("删除失败: " + err.message);
      }
      resp.ok({ deletedCount: result.affectedRows }, "删除成功");
    });
  } catch (error) {
    console.error("删除异常:", error);
    resp.err("删除失败: " + error.message);
  }
};

// 修改招聘计划
exports.updateRecruitmentPlan = (req, resp) => {
  try {
    const planInfo = req.body;

    if (!planInfo.id) return resp.err("记录ID不能为空");

    // 构建更新数据
    const updateData = {};
    const allowedFields = [
      "post",
      "requirement",
      "num",
      "staff_no",
      "staff_name",
      "position",
      "department_name",
      "process",
      "time",
      "audit",
      "review_responses",
    ];

    allowedFields.forEach((field) => {
      if (planInfo[field] !== undefined) {
        updateData[field] = planInfo[field];
      }
    });

    if (Object.keys(updateData).length === 0) {
      return resp.err("未提供修改字段");
    }

    const updateSql = "UPDATE recruitmentplan SET ? WHERE id = ?";
    db.query(updateSql, [updateData, planInfo.id], (err, result) => {
      if (err) {
        console.error("更新失败:", err);
        return resp.err("更新失败: " + err.message);
      }
      if (result.affectedRows === 0) return resp.err("未找到记录");

      // 返回更新后的数据
      const selectSql = "SELECT * FROM recruitmentplan WHERE id = ?";
      db.query(selectSql, [planInfo.id], (err, rows) => {
        if (err) return resp.err("查询失败");
        resp.ok(rows[0], "更新成功");
      });
    });
  } catch (error) {
    console.error("更新异常:", error);
    resp.err("更新失败: " + error.message);
  }
};

// 特别审核接口
exports.auditPlan = (req, resp) => {
  try {
    const { id, auditStatus, reviewResponse } = req.body;

    if (!id) return resp.err("记录ID不能为空");
    if (auditStatus === undefined) return resp.err("审核状态不能为空");

    const updateData = {
      audit: auditStatus,
      review_responses: reviewResponse || null,
    };

    const updateSql = "UPDATE recruitmentplan SET ? WHERE id = ?";
    db.query(updateSql, [updateData, id], (err, result) => {
      if (err) {
        console.error("审核失败:", err);
        return resp.err("审核失败: " + err.message);
      }
      resp.ok(null, "审核操作已完成");
    });
  } catch (error) {
    console.error("审核异常:", error);
    resp.err("审核失败: " + error.message);
  }
};
